package com.example.todotask.activity;

import java.util.GregorianCalendar;

import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.text.format.DateFormat;
import android.view.Menu;

import com.example.todotask.R;
import com.example.todotask.model.Task;
import com.example.todotask.ultils.Constant;
import com.example.todotask.ultils.ToastMessage;

public class AddTaskActivity extends BaseActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		// khoi tao repeat type spinner
		drpRepeatType.setSelection(Constant.DAYS);
	}

	/**
	 * Tao menu item
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.add_task, menu);
		return true;
	}

	/**
	 * Thực hiện thêm mới một task.
	 */
	@Override
	protected boolean addTask() {
		try {
			// validate input task.
			if (!isValidInput()) {
				return false;
			}
			
			// get value task info
			String name = editTaskName.getText().toString().trim();
			String note = editTaskNote.getText().toString().trim();
			String dueDate = (String) DateFormat.format(
					Constant.DATE_TIME_FORMAT, due_date_cal);
			int repeatType = drpRepeatType.getSelectedItemPosition();
			int completion = 0;
			if (due_date_cal.getTimeInMillis() > System.currentTimeMillis()) {
				completion = Constant.TASK_NOT_COMPLETION;
			} else {
				completion = Constant.TASK_COMPLETION;
			}
			String androidId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
			String deviceId = androidId;
			String createdDate = (String) DateFormat.format(
					Constant.DATE_TIME_FORMAT, GregorianCalendar.getInstance());
			
			long _id = db.getNextID();
			task = new Task(_id, name, note, dueDate, repeatType, completion,
					deviceId, createdDate, createdDate);
			
			// thực hiện add.
			long taskId = taskHandler.insert(task);
			if (taskId > 0) {
				// thêm thành công.
				ToastMessage.ToastMsg(this, R.string.toast_msg_add_task_success);
				
				// TODO set reminder
				
				// back ve activity main
				intent = new Intent(this, MainActivity.class);
				intent.putExtra(Constant.EXTRA_TASK_ID, taskId);
				
				return true;
			}
			
			// them that bai.
			ToastMessage.ToastMsg(this, R.string.toast_msg_add_task_failed);
			return false;
		} catch (Exception e) {
			ToastMessage.ToastMsg(this, R.string.toast_err_system_processing);
			return false;
		}
	}
}
